<style scoped lang="scss">
.explain-block {
  div {
    font-weight: 700;
    font-size: 14px;
  }
  p {
    margin: 5px;
    font-size: 12px;
    text-indent: 2em;
  }
}
.dialog__body {
  background-color: #f3f3fa;
  border: 1px solid #bbbbbb;
  height: 65vh;
  overflow-y: auto;
  position: relative;
  display: flex;
  flex-direction: column;
}

.button-group {
  margin: 20px 0 0 10px;
  display: flex;
  justify-content: space-between;

  &__info {
    margin-right: 10px;
  }
}

.tab-group {
  margin: 10px 0 0 0;
  height: 100%;

  ::v-deep .el-tabs__nav-wrap {
    padding: 10px 10px 0 10px;
  }

  ::v-deep .el-tabs__nav-wrap:after {
    height: 0;
  }

  ::v-deep .el-tabs__header {
    margin: 0;
  }

  ::v-deep .el-tabs__nav-scroll {
    background-color: #ffffff;
  }

  ::v-deep .el-tabs__nav {
    margin-left: 10px;
  }

  ::v-deep .el-tab-pane {
    padding: 0 10px;
  }

  ::v-deep .el-table th.is-leaf {
    background-color: #f3f3fa !important;
  }
}

.button-group__footer {
  display: flex;
  flex-direction: row-reverse;
  margin: 20px 10px 10px 0;
  //position: absolute;
  //bottom: 5px;
  //right: 0;
  &__cancel {
    margin: 0 0 0 10px;
  }
}
</style>
<template>
  <div class="dialog__body">
    <div class="button-group">
      <div class="button-group__operator">
        <mine-button type="primary" @click="fileUpload"
          ><i class="iconfont icon-upload-line"></i>文件上传
        </mine-button>
        <mine-button type="primary" secondary @click="deleteAll"
          ><i class="iconfont icon-delete-line"></i>全部删除</mine-button
        >
      </div>
      <el-popover placement="right" width="200" trigger="click">
        <div class="explain-block">
          <div>功能：</div>
          <p>{{ explainData.funDescription }}</p>
          <div>输入端口：</div>
          <p>{{ explainData.inPort }}</p>
          <div>输出端口：</div>
          <p>{{ explainData.outPort }}</p>
          <div>参数：</div>
          <p>{{ explainData.functionName }}</p>
        </div>
        <mine-button
          slot="reference"
          type="primary"
          class="button-group__info"
          @click="getExplainInfo('fileUpload')"
          ><i class="iconfont icon-help-circle-line"></i>说明</mine-button
        >
      </el-popover>
    </div>
    <div class="tab-group">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="数据内容" name="content">
          <el-table
            class="table border-table"
            :data="leftTableData"
            style="width: 100%"
            :header-cell-style="{ background: '#f3f3fa' }"
            v-loading="loading"
            :height="tableHeight"
            ref="multipleTable"
          >
            <el-table-column
              v-for="(item, index) in leftLabels"
              :key="index"
              :label="item"
              :prop="item"
              show-overflow-tooltip
              width=""
            >
              <template slot-scope="scope">
                <span>{{ at(scope.row, item)[0] }}</span>
              </template>
            </el-table-column>
          </el-table>
          <!--                    <mine-pagination-->
          <!--                        @numberChange="numberChange"-->
          <!--                        :total="total"-->
          <!--                        :page-size="pageSize"-->
          <!--                        :current-page="currentPage">-->
          <!--                    </mine-pagination>-->
        </el-tab-pane>
        <el-tab-pane label="数据结构" name="structure">
          <el-table
            class="table border-table"
            :data="rightTableData"
            style="width: 100%"
            v-loading="loading"
            :height="tableHeight"
            ref="multipleTable"
          >
            <el-table-column
              key="name"
              label="名称"
              prop="name"
              show-overflow-tooltip
              width=""
            >
            </el-table-column>
            <el-table-column
              key="type"
              label="类型"
              prop="type"
              show-overflow-tooltip
              width=""
            >
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div class="button-group__footer">
      <mine-button
        type="primary"
        secondary
        class="button-group__footer__cancel"
        @click="cancel"
        >取消</mine-button
      >
      <mine-button type="primary" @click="confirm">确定</mine-button>
    </div>
    <mine-dialog
      :top="'10vh'"
      :appendToBody="true"
      :dialogFormVisible="flag"
      :width="'900px'"
      :modalFlag="modalFlag"
      :title="title"
      :showClose="showClose"
      @close="close"
    >
      <div slot="option">
        <el-form ref="form" :model="form" :rules="rules" label-width="110px">
          <el-form-item label="上传数据：" :required="true">
            <mine-upload
              ref="upload"
              :fileType="accept"
              @change="onChange"
            ></mine-upload>
            <span style="font-weight: 700">仅支持横向表格标题文件！</span>
          </el-form-item>
          <mine-button type="primary" @click="submitUpload"
            >确认上传</mine-button
          >
        </el-form>
      </div>
    </mine-dialog>
  </div>
</template>

<script>
import qs from "qs";
import { at } from "lodash";
import { QWebChannel } from "@/modules/index/utils/qwebchannel.js";

export default {
  name: "InputOpera",
  data() {
    return {
      loading: false,
      leftTableData: [],
      rightTableData: [],
      activeName: "content",
      flag: false,
      modalFlag: false,
      title: "文件上传",
      showClose: true,
      form: {},
      rules: {},
      leftLabels: [],
      rightLabels: ["name", "type"],
      explainData: {}, // 说明信息
      at,
      debounceTimer: null, // 确认键防抖定时器
    };
  },
  props: {
    currentOperatorData: {
      type: Object,
    },
    currentProcessId: {
      type: String,
    },
  },
  computed: {
    tableHeight: function () {
      return 0.45 * window.innerHeight + "px";
    },
    accept() {
      return ".txt,.xls,.xlsx,.csv";
    },
  },
  methods: {
    async getExplainInfo(type) {
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: `/helpInfo/getTree?helpCode=${type}`,
              RequestMethod: "get",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: {},
              isStringParam: true,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              _self.explainData = result?.data;
            } else {
              _self.$message.warning("获取说明信息失败！");
            }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          `/helpInfo/getTree?helpCode=${type}`,
          "get",
          "application/json;charset=UTF-8",
          {},
          true,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            // TODO： 定制后台数据处理
            if (res.status === 200 && e.data.webInfo.requestId === uuid) {
              this.explainData = res?.data;
            } else {
              this.$message.warning("获取说明信息失败！");
            }
          },
          { once: true }
        );
      } else {
        const res = await this.$store.dispatch("getOperatorExplain", type);
        if (res.data.success) {
          this.explainData = res.data?.data;
        } else {
          this.$message.warning("获取说明信息失败！");
        }
      }
    },
    // 删除全部按钮
    async deleteAll() {
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: `/feDatafile/deleteByIds?ids=${_self.rightTableData[0].datafileId}`,
              RequestMethod: "post",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: {},
              isStringParam: false,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              _self.leftTableData = [];
              _self.rightTableData = [];
              _self.$message.success(result.msg);
            } else {
              _self.$message.error(result.msg);
            }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          `/feDatafile/deleteByIds?ids=${this.rightTableData[0].datafileId}`,
          "post",
          "application/json;charset=UTF-8",
          {},
          false,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res;
            res = e.data;
            const result = res.response || {};
            if (result.status === 200) {
              this.leftTableData = [];
              this.rightTableData = [];
              this.$message.success(result.msg);
            } else {
              this.$message.error(result.msg);
            }
          },
          {
            once: true,
          }
        );
      } else {
        const res = await this.$store.dispatch(
          "uploadFileDeleteAll",
          this.rightTableData[0].datafileId
        );
        if (res.data.status === 200) {
          this.leftTableData = [];
          this.rightTableData = [];
          this.$message.success(res.data.msg);
        } else {
          this.$message.error(res.data.msg);
        }
      }
    },
    handleClick(tab, event) {
      // console.log(tab, event);
    },
    cancel() {
      // this.dialogFlag = false
      this.$emit("changeFlag");
    },
    async confirm() {
      // 防抖处理
      if (this.debounceTimer !== null) {
        clearTimeout(this.debounceTimer);
      }
      this.debounceTimer = setTimeout(async () => {
        let res = {};
        let _self = this;
        if (_self.$qwebUtil.isQtClient) {
          const uuid = _self.$qwebUtil.generateRandomUUID();
          let sendObject;
          /* eslint-disable-next-line */
          const channel = new QWebChannel(
            window.qt.webChannelTransport,
            async function (channel) {
              sendObject = channel.objects.sendObject;
              // receivedJSON 修改此处发送请求参数
              const receivedJSON = {
                RequestUrl: `/feDatafile/analyzeSave?id=${_self.rightTableData[0].datafileId}`,
                RequestMethod: "post",
                ContentType: "application/json;charset=UTF-8",
                RequestBody: {},
                isStringParam: false,
                requestId: uuid,
              };
              await send();
              await _self.$qwebUtil.receive(sendObject, receivedJSON);
              // console.error('received','/feCanvas/pageList')
            }
          );
          /* eslint-disable-next-line */
          async function send() {
            sendObject.sendMessage.connect(function (data) {
              if (!data) {
                console.error("No data received.");
              }
              res = JSON.parse(data);
              const result = res.response || {};
              // update the followings
              if (result.success && res.webInfo.requestId == uuid) {
                _self.$message.success("保存成功");
                _self.$emit("changeFlag");
                _self.$emit("getFileDataList");
              } else {
                _self.$message.error("保存失败");
              }
            });
          }
        } else if (this.$webview2.isWPF) {
          const uuid = this.$webview2.generateRandomUUID();
          await this.$webview2.sendWebView2(
            `/feDatafile/analyzeSave?id=${this.rightTableData[0].datafileId}`,
            "post",
            "application/json;charset=UTF-8",
            {},
            false,
            uuid
          );
          await window.chrome.webview.addEventListener(
            "message",
            (e) => {
              let res = e.data.response;
              // TODO： 定制后台数据处理
              if (res.status === 200) {
                this.$message.success("保存成功");
                this.$emit("changeFlag");
                this.$emit("getFileDataList");
              } else {
                this.$message.error("保存失败");
              }
            },
            { once: true }
          );
        } else {
          const res = await this.$store.dispatch(
            "postUpload",
            this.rightTableData[0].datafileId
          );
          if (res.status === 200) {
            this.$message.success("保存成功");
            this.$emit("changeFlag");
            this.$emit("getFileDataList");
          } else {
            this.$message.error("保存失败");
          }
        }
      }, 500);
    },
    fileUpload() {
      this.flag = true;
    },
    close() {
      this.flag = false;
    },
    onChange(data) {
      this.form.file =
        data.fileList && data.fileList.length ? data.fileList[0] : "";
      this.fileList =
        data.fileList && data.fileList.length ? data.fileList : [];
    },
    async submitUpload() {
      let params = {};
      let formData = new FormData();
      formData.append("file", this.form.file.raw);
      params.formData = formData;
      params.processingId = this.currentOperatorData.id;
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        // 这里对文件的处理需要转成base64的格式后上传
        let reader = new FileReader();
        reader.readAsDataURL(this.form.file.raw);
        reader.onload = async (e) => {
          params.formData = e.target.result;
          const uuid = _self.$qwebUtil.generateRandomUUID();
          let sendObject;
          /* eslint-disable-next-line */
          const channel = new QWebChannel(
            window.qt.webChannelTransport,
            async function (channel) {
              sendObject = channel.objects.sendObject;
              // receivedJSON 修改此处发送请求参数
              const receivedJSON = {
                RequestUrl: `/feDatafile/uploadAnalyze?processingId=${params.processingId}&username=haha&iteminfoId=1111&txtMethod=1`,
                RequestMethod: "post",
                ContentType: "multipart/form-data",
                RequestBody: {
                  file: params.formData,
                  fileName: _self.form.file.name,
                },
                isStringParam: false,
                requestId: uuid,
              };
              await send();
              await _self.$qwebUtil.receive(sendObject, receivedJSON);
              // console.error('received','/feCanvas/pageList')
            }
          );
          /* eslint-disable-next-line */
          async function send() {
            sendObject.sendMessage.connect(function (data) {
              if (!data) {
                console.error("No data received.");
              }
              res = JSON.parse(data);
              const result = res.response || {};
              // update the followings
              if (result.success && res.webInfo.requestId == uuid) {
                _self.leftLabels = Object.keys(result?.data.data[0]);
                _self.leftTableData = result?.data.data;
                _self.rightTableData = result?.data.type;
                _self.flag = false;
              } else {
                _self.$message.error(result.msg);
              }
            });
          }
        };
      } else if (this.$webview2.isWPF) {
        // 这里对文件的处理需要转成base64的格式后上传
        let reader = new FileReader();
        reader.readAsDataURL(this.form.file.raw);
        reader.onload = async (e) => {
          params.formData = e.target.result;
          const uuid = this.$webview2.generateRandomUUID();
          await this.$webview2.sendWebView2(
            `/feDatafile/uploadAnalyze?processingId=${params.processingId}&username=haha&iteminfoId=1111&txtMethod=1`,
            "post",
            // "application/json;charset=UTF-8",
            "multipart/form-data",
            {
              file: params.formData,
              fileName: this.form.file.name,
            },
            // formData,
            false,
            uuid
          );
          await window.chrome.webview.addEventListener(
            "message",
            (e) => {
              let res = e.data.response;
              // TODO： 定制后台数据处理
              if (res.status === 200) {
                this.leftLabels = Object.keys(res?.data.data[0]);
                this.leftTableData = res?.data.data;
                this.rightTableData = res?.data.type;
                this.flag = false;
              } else {
                this.$message.error(res.msg);
              }
            },
            {
              once: true,
              capture: true,
            }
          );
        };
      } else {
        try {
          const res = await this.$store.dispatch("uploadAnalyze", params);
          if (res.data.status === 200) {
            this.leftLabels = Object.keys(res?.data?.data.data[0]);

            // this.rightLabels = Object.keys(res?.data?.data.type[0]);

            this.leftTableData = res?.data?.data.data;
            this.rightTableData = res?.data?.data.type;
            this.flag = false;
          } else {
            this.$message.error(res.data.msg);
          }
        } catch (e) {
          console.error(e);
        }
      }
    },
    async feDatafield() {
      const params = {
        id: this.$route.query.id,
      };
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: "/feCanvas/pageList",
              RequestMethod: "get",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: qs.stringify(params, { indices: false }),
              isStringParam: true,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              _self.$message.success("读取原始文件成功");
            } else {
              _self.$message.error("读取原始文件失败");
            }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          "/feCanvas/pageList",
          "get",
          "application/json;charset=UTF-8",
          qs.stringify(params, { indices: false }),
          true,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            // TODO： 定制后台数据处理
            if (res.status === 200 && e.data.webInfo.requestId === uuid) {
              // console.log(res.data);
            } else {
              this.$message.error("读取原始文件失败");
            }
          },
          { once: true }
        );
      } else {
        try {
          // console.log(params);
          const res = await this.$store.dispatch(
            "feDatafileGetById",
            qs.stringify(params, { indices: false })
          );
          const result = res.data || {};
          // TODO： 定制后台数据处理
          // console.log(result,'1')
          if (result.success) {
            // console.log(result);
          } else {
            this.$message.error("读取原始文件失败");
          }
        } catch (e) {
          console.error(e);
        }
      }
    },
    // 回显文件上传两个列表的数据
    async getTwoTablesDataList() {
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: "/feDatafile/getTreeByProcessId",
              RequestMethod: "get",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: qs.stringify(
                { processingId: _self.currentOperatorData.id },
                { indices: false }
              ),
              isStringParam: true,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              _self.leftLabels = Object.keys(result.data.data[0]);
              _self.leftTableData = result.data.data;
              _self.rightTableData = result.data.type;
            } else {
              _self.$message.error("获取文件上传数据失败");
            }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          "/feDatafile/getTreeByProcessId",
          "get",
          "application/json;charset=UTF-8",
          qs.stringify(
            { processingId: this.currentOperatorData.id },
            { indices: false }
          ),
          true,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            // TODO： 定制后台数据处理
            if (res.status === 200 && e.data.webInfo.requestId === uuid) {
              this.leftLabels = Object.keys(res.data.data[0]);
              this.leftTableData = res.data.data;
              this.rightTableData = res.data.type;
            } else {
              this.$message.error("获取文件上传数据失败");
            }
          },
          { once: true }
        );
      } else {
        const res = await this.$store.dispatch(
          "getInputTableByOperatorId",
          this.currentOperatorData.id
        );
        if (res.data?.status === 200) {
          this.leftLabels = Object.keys(res?.data?.data?.data[0]);
          this.leftTableData = res?.data?.data?.data;
          this.rightTableData = res?.data?.data?.type;
        } else {
          this.$message.error("获取文件上传数据失败");
        }
      }
    },
  },
  mounted() {
    // this.feDatafield();
    // setTimeout(() => {
    this.getTwoTablesDataList();
    // }, 200);
  },
};
</script>


